package com.ray.controller;

import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.appengine.api.search.query.QueryParser.item_return;
import com.google.appengine.repackaged.com.google.api.client.util.ArrayMap;
import com.google.appengine.repackaged.org.joda.time.DateTime;
import com.mysql.fabric.xmlrpc.base.Array;
import com.ray.bean.AttendApprovalLeaveBean;
import com.ray.bean.AttendApprovalOvertimeBean;
import com.ray.bean.AttendApprovalProcessBean;
import com.ray.bean.AttendApprovalProcessUniteBean;
import com.ray.bean.AttendClassTailBean;
import com.ray.bean.AttendanceClassBean;
import com.ray.bean.AttendanceGroupBean;
import com.ray.bean.DatatablesViewPageBean;
import com.ray.bean.PersonBean;
import com.ray.exception.ServiceException;
import com.ray.pojo.AttendDevicePojo;
import com.ray.pojo.AttendQueryDailyStatisticsPojo;
import com.ray.pojo.AttendSourceRecordExportPojo;
import com.ray.pojo.AttendSourceRecordPojo;
import com.ray.pojo.MyUser;
import com.ray.pojo.attend.ClockTimePojo;
import com.ray.pojo.attend.FillcardApplicationPojo;
import com.ray.pojo.attend.LeaveApplicationPojo;
import com.ray.pojo.attend.OvertimeApplicationPojo;
import com.ray.pojo.attend.OvertimeRulePojo;
import com.ray.pojo.attend.SummaryBodyPojo;
import com.ray.service.BasicDataService;
import com.ray.service.DingTalkService;
import com.ray.service.DisplayViewService;
import com.ray.service.ScheduleService;
import com.ray.service.WeiXinService;
import com.ray.util.AttendanceUtil;
import com.ray.util.ExcelExportUtil;
import com.ray.util.RequestUtil;
import com.ray.util.ResponseUtil;
import com.ray.util.ReturnStringUtil;
import com.ray.util.TimeAndUnix;
import com.ray.util.redis.RedisCache;
import com.ray.util.weixin.WeixinTemplateList;
import com.ray.util.weixin.WeixinTemplateSender;

@SuppressWarnings({"unchecked","rawtypes"})
@Controller
@RequestMapping("/dingTalk")
public class DingTalkController {
	@Autowired
	DingTalkService dingTalkService;
	@Autowired
	ScheduleService scheduleService;
	@Autowired
	DisplayViewService displayViewService;
	@Autowired
	BasicDataService basicDataService;
	@Autowired
	WeiXinService weiXinService;
	
	
	/**
	 * 考勤看板退出登录
	 * @param request
	 * @param token
	 * @return String
	 * @throws ParseException
	 * @author 王荣
	 */
	@RequestMapping("/attendBoardloginOut")
	public String AttendBoardloginOut(HttpServletRequest request,String token) throws ParseException {
		request.getSession().setAttribute("userLogin", null);
		return "redirect:/attendBoard/login.html";
	}
	/**
	 * 获取补卡审批人员（该职员所属部门的部门经理）
	 * @param request
	 * @return
	 * @throws ServiceException  
	 * @author 王荣
	 * @date 2018年6月2日 下午1:40:47
	 */
	@RequestMapping("getFillCardApprover")
	@ResponseBody
	public Map<String,Object>  getFillCardApprover(HttpServletRequest request) throws ServiceException {
		Map<String,Object> map = RequestUtil.getRequestParamByGeneric(request);
		return ResponseUtil.ResponseResult(dingTalkService.getFillCardApprover(map));
	}
	/**
	 * 根据人员id与日期获取考勤信息   
	 * @param request
	 * @throws ServiceException  
	 * @author 王荣
	 * @throws ParseException 
	 */
	@RequestMapping("/getUserAttendInfo")
	@ResponseBody
	public Map<String,Object> getUserAttendInfo(HttpServletRequest request) throws ServiceException, ParseException {
		Map<String,Object> map = RequestUtil.getRequestParamByGeneric(request);
		return ResponseUtil.ResponseResult(dingTalkService.getUserAttendInfo(map));
	}
	/**
	 * 获取考勤结果信息
	 * @param request
	 * @return
	 * @throws ServiceException
	 * @author 王荣
	 */
	@RequestMapping("/getClockResult")
	@ResponseBody
	public Map getClockResult(HttpServletRequest request) throws ServiceException {
		Map map = RequestUtil.getRequestAllParam(request);
		return ResponseUtil.ResponseResult(dingTalkService.getClockResult(map));
	}
	/**
	 * 获取奖惩制度信息
	 * @param request
	 * @return
	 * @throws ServiceException
	 * @author 王荣
	 */
	@RequestMapping("/getRewardAndPunishInfo")
	@ResponseBody
	public Map getRewardAndPunishInfo(HttpServletRequest request) throws ServiceException {
		Map map = RequestUtil.getRequestAllParam(request);
		return ResponseUtil.ResponseResult(dingTalkService.getRewardAndPunishInfo(map));
	}
	/**
	 * 考勤奖惩设置
	 * @param array1
	 * @param array2
	 * @param array3
	 * @param array4
	 * @param array5
	 * @param request
	 * @return
	 * @throws ServiceException
	 * @author 王荣
	 */
	@RequestMapping("/rewardAndPunishSet")
	@ResponseBody
	public Map rewardAndPunishSet(Integer[] array1,Double[] array2,Double[] array3,Double[] array4,Double[] array5,HttpServletRequest request) throws ServiceException {
		MyUser myUser=RequestUtil.getLoginUser(request);
		String loginCompany = myUser.getCompany();
		Map map = new HashMap();
		map.put("array1", array1);
		map.put("array2", array2);
		map.put("array3", array3);
		map.put("array4", array4);
		map.put("array5", array5);
		map.put("loginCompany", loginCompany);
		System.out.println("myuser.getCompany:"+loginCompany);
		dingTalkService.rewardAndPunishSet(map);
		return ResponseUtil.ResponseResult(ReturnStringUtil.SET_SUCCESS);
	}
	/**
	 * 获取加班规则考勤组名称
	 * @param groupIds
	 * @return
	 * @author 王荣
	 */
	@RequestMapping("/getGroupName")
	@ResponseBody
	public Map getGroupName(String groupIds) {
		return ResponseUtil.ResponseResult(dingTalkService.getGroupName(groupIds));
	}
	/**
	 * 根据考勤组id查询考勤组信息
	 */
	@RequestMapping("/getGroupDetail")
	@ResponseBody
	public Map getGroupDetail(String id) {
		return ResponseUtil.ResponseResult(dingTalkService.getGroupDetail(id));
	}
	/**
	 * 删除考勤组
	 * @param id
	 * @return
	 * @author 王荣
	 */
	@RequestMapping("/deleteGroup")
	@ResponseBody
	public Map deleteGroup(String id) {
		dingTalkService.deleteGroup(id);
		return ResponseUtil.ResponseResult(ReturnStringUtil.DELETE_SUCCESS);
	}
	/**
	 * 修改考勤组
	 * @param request
	 * @return
	 * @throws ServiceException
	 * @author 王荣
	 */
	@RequestMapping("/updateGroup")
	@ResponseBody
	public Map updateGroup(HttpServletRequest request) throws ServiceException {
		Map map=RequestUtil.getRequestAllParam(request);
		dingTalkService.updateGroup(map);
		return ResponseUtil.ResponseResult(ReturnStringUtil.UPDATE_SUCCESS);
	}
	/**
	 * 根据班次id查询班次名称+时间
	 * @param classId
	 * @return
	 * @throws ServiceException
	 * @throws ParseException
	 * @author 王荣
	 */
	@RequestMapping("/selectClassById")
	@ResponseBody
	public Map selectClassById(String classId) throws ServiceException, ParseException {
		return ResponseUtil.ResponseResult(dingTalkService.selectClassById(classId));
	}
	/**
	 * 根据部门id查询部门人数
	 * @param deptId
	 * @return
	 * @throws ServiceException
	 * @throws ParseException
	 * @author 王荣
	 */
	@RequestMapping("/selectCountById")
	@ResponseBody
	public Map selectCountById(String deptId) throws ServiceException, ParseException {
		return ResponseUtil.ResponseResult(dingTalkService.selectCountById(deptId));
	}
	/**
	 * 查询考勤组
	 * @param request
	 * @return
	 * @throws ServiceException
	 * @throws ParseException
	 * @author 王荣
	 */
	@RequestMapping("/queryGroup")
	@ResponseBody
	public DatatablesViewPageBean queryGroup(HttpServletRequest request) throws ServiceException, ParseException {
		Map map=RequestUtil.getRequestAllParam(request);
		return dingTalkService.queryGroup(map);
	}
	/**
	 * 插入班次
	 * @param attendanceGroupBean
	 * @param request
	 * @return
	 * @throws ServiceException
	 * @throws ParseException
	 * @author 王荣
	 */
	@RequestMapping("/insertGroup")
	@ResponseBody
	public Map insertGroup(AttendanceGroupBean attendanceGroupBean,HttpServletRequest request) throws ServiceException, ParseException {
		Map map=RequestUtil.getRequestAllParam(request);
		dingTalkService.insertGroup(map);
		return ResponseUtil.ResponseResult(ReturnStringUtil.ADD_SUCCESS);
	}
	/**
	 * 根据部门名称获取相应的职员
	 * @param request
	 * @return
	 * @throws ServiceException
	 * @author 王荣
	 */
	@RequestMapping("/getPersonName")
	@ResponseBody
	public DatatablesViewPageBean getPersonName(HttpServletRequest request) throws ServiceException {
		Map map=RequestUtil.getRequestAllParam(request);
		return dingTalkService.getPersonName(map);
	}
	/**
	 * 查询部门
	 * @param request
	 * @return
	 * @throws ServiceException
	 * @throws ParseException
	 * @author 王荣
	 */
	@RequestMapping("/queryDept")
	@ResponseBody
	public DatatablesViewPageBean queryDept(HttpServletRequest request) throws ServiceException, ParseException {
		Map map=RequestUtil.getRequestAllParam(request);
		return dingTalkService.queryDept(map);
	}
	/**
	 * 修改班次
	 * @param attendanceClass
	 * @param request
	 * @return
	 * @throws ServiceException
	 * @throws ParseException
	 * @author 王荣
	 */
	@RequestMapping("/updateClass")
	@ResponseBody
	public Map updateClass(AttendanceClassBean attendanceClass,HttpServletRequest request) throws ServiceException, ParseException {
		RequestUtil.getLoginUser(request);
		dingTalkService.updateClass(attendanceClass);
		return ResponseUtil.ResponseResult(ReturnStringUtil.UPDATE_SUCCESS);
	}
	/**
	 * 删除对应公司的班次
	 * @param request
	 * @param id
	 * @return
	 * @throws ServiceException
	 * @throws ParseException
	 * @author 王荣
	 */
	@RequestMapping("/deleteClass")
	@ResponseBody
	public Map deleteClass(HttpServletRequest request,String id) throws ServiceException, ParseException {
		MyUser myuser=RequestUtil.getLoginUser(request);
		dingTalkService.deleteClass(myuser,id);
		return ResponseUtil.ResponseResult(ReturnStringUtil.DELETE_SUCCESS);
	}
	/**
	 * 获取班次名称，用于校验班次名称是否重复
	 * @param request
	 * @return
	 * @throws ServiceException
	 * @throws ParseException
	 * @author 王荣
	 */
	@RequestMapping("/queryClassName")
	@ResponseBody
	public Map queryClassName(HttpServletRequest request) throws ServiceException, ParseException {
		MyUser myuser=RequestUtil.getLoginUser(request);
		return ResponseUtil.ResponseResult(dingTalkService.queryClassName(myuser));
	}
	/**
	 * 查询考勤班次
	 * @param request
	 * @throws ServiceException
	 * @throws ParseException
	 * @author 王荣
	 */
	@RequestMapping("/queryClass")
	@ResponseBody
	public DatatablesViewPageBean queryClass(HttpServletRequest request) throws ServiceException, ParseException {
		Map map=RequestUtil.getRequestAllParam(request);
		return dingTalkService.queryClass(map);
	}
	/**
	 * 插入班次
	 * @param attendanceClass
	 * @param request
	 * @throws ServiceException
	 * @throws ParseException
	 * @author 王荣
	 */
	@RequestMapping("/insertClass")
	@ResponseBody
	public Map insertClass(AttendanceClassBean attendanceClass,HttpServletRequest request) throws ServiceException, ParseException {
		MyUser myuser=RequestUtil.getLoginUser(request);
		dingTalkService.insertClass(attendanceClass,myuser);
		return ResponseUtil.ResponseResult(attendanceClass.getId());
	}
	/**
	 * 根据日期查询钉钉考勤数据
	 * @param request
	 * @throws ServiceException
	 * @throws ParseException
	 * @author 王荣
	 */
	@RequestMapping("/queryAttendance")
	@ResponseBody
	public DatatablesViewPageBean<AttendSourceRecordPojo> queryAttendance(HttpServletRequest request) throws ServiceException, ParseException {
		Map<String,Object> map=RequestUtil.getRequestParamByGeneric(request);
		return dingTalkService.queryAttendance(map);
	}
	
	/**
	 * 根据日期查询无效打卡时间
	 * @param request
	 * @throws ServiceException
	 * @throws ParseException
	 * @author 王荣
	 */
	@RequestMapping("/queryAttendanceInvalid")
	@ResponseBody
	public DatatablesViewPageBean<AttendSourceRecordPojo> queryAttendanceInvalid(HttpServletRequest request) throws ServiceException, ParseException {
		Map<String,Object> map=RequestUtil.getRequestParamByGeneric(request);
		return dingTalkService.queryAttendanceInvalid(map);
	}
	
	/**
	 * 导出无效打卡时间原始记录
	 * @param request
	 * @return
	 * @author 王荣
	 */
	@RequestMapping(value="/exprotExcelAttendSourceInvalidRecord",method=RequestMethod.GET)
	@ResponseBody
	public void exprotExcelAttendSourceInvalidRecord(HttpServletRequest request,HttpServletResponse response) throws ServiceException, CloneNotSupportedException, NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException, IOException{
		ObjectMapper MAPPER = new ObjectMapper();
		Map<String,Object> map=RequestUtil.getRequestParamByGeneric(request);
		map.put("start", null);
		map.put("length", null);
		DatatablesViewPageBean<AttendSourceRecordPojo> datatablesViewPageBean=dingTalkService.queryAttendanceInvalid(map);
		List<AttendSourceRecordPojo> tableList= datatablesViewPageBean.getReturnData();
		//用于打印的数据
		List<AttendSourceRecordExportPojo> list = new ArrayList<AttendSourceRecordExportPojo>();
		//转换对象
		for(AttendSourceRecordPojo attendSourceRecordPojo : tableList) {
			String jsonStr = MAPPER.writeValueAsString(attendSourceRecordPojo);
			AttendSourceRecordExportPojo detail = MAPPER.readValue(jsonStr , AttendSourceRecordExportPojo.class);
			list.add(detail);
		}
		//表头字段
		String [] tableHeadFields={"姓名","部门","车间","工号","考勤日期","打卡有效开始时间","打卡有效结束时间","打卡时间","考勤结果","打卡地点"};
		//对应的内容字段
		String [] fields={"userName","deptName","workshopName","userId","workdate","baseCheckStartTime","baseCheckEndTime","userCheckTime","timeResult","location"};
		String tempFolder=request.getServletContext().getRealPath("/")+"tempExcelFolder";
		File excelFile=ExcelExportUtil.createExcelFileWithStyle(list,tempFolder,tableHeadFields,fields,"原始记录");
		ResponseUtil.downloadfile(response, excelFile, "考勤原始记录表.xlsx", true);
	}
	
	
	/**
	 * 提交请假单
	 * @param request
	 * @throws ParseException
	 * @author 王荣
	 */
	@RequestMapping("/submitLeaveApplication")
	@ResponseBody
	public Map<String,Object> submitLeaveApplication(HttpServletRequest request) throws ParseException  {
		Map<String,Object> map=RequestUtil.getRequestParamByGeneric(request);
		return ResponseUtil.ResponseResult(dingTalkService.submitLeaveApplication(map));
	}
	/**
	 * askForApprover获取请假可审批人，type=1请假审批，type=2补卡审批 
	 * 不传或type对应的审批类型没有设置则获取公司所有员工，员工自行判断自由选择审批人
	 */
	@RequestMapping("/askForApprover")
	@ResponseBody
	public Map<String,Object> askForApprover(HttpServletRequest request) {
		Map<String,Object> map=RequestUtil.getRequestParamByGeneric(request);
		return ResponseUtil.ResponseResult(dingTalkService.askForApprover(map));
	}
	/**
	 * 查询审批人流程设置
	 * @param request
	 * @return
	 * @throws ServiceException
	 * @author 王荣
	 */
	@RequestMapping("/queryApprovalProcessSet")
	@ResponseBody
	public DatatablesViewPageBean<AttendApprovalProcessBean> queryApprovalProcessSet(HttpServletRequest request) throws ServiceException {
		Map<String,Object> map=RequestUtil.getRequestParamByGeneric(request);
		return dingTalkService.queryApprovalProcessSet(map);
	}
	
	/**
	 * 查询审批人流程设置 统一设置
	 * @param request
	 * @return
	 * @throws ServiceException
	 * @author 王荣
	 */
	@RequestMapping("/queryApprovalProcessSetForUnite")
	@ResponseBody
	public DatatablesViewPageBean<AttendApprovalProcessUniteBean> queryApprovalProcessSetForUnite(HttpServletRequest request) throws ServiceException {
		Map<String,Object> map=RequestUtil.getRequestParamByGeneric(request);
		return dingTalkService.queryApprovalProcessSetForUnite(map);
	}
	
	/**
	 * 查询审批人流程设置 统一设置
	 * @param request
	 * @return
	 * @throws ServiceException
	 * @author 王荣
	 */
	@RequestMapping("/insertApprovalProcessSetForUnite")
	@ResponseBody
	public Map<String,Object> insertApprovalProcessSetForUnite(HttpServletRequest request) throws ServiceException {
		Map<String,Object> map=RequestUtil.getRequestParamByGeneric(request);
		dingTalkService.insertApprovalProcessSetForUnite(map);
		return ResponseUtil.ResponseResult(ReturnStringUtil.UPDATE_SUCCESS);
	}
	
	/**
	 * 审批人设置
	 * @param request
	 * @author 王荣
	 */
	@RequestMapping("/addAndDeleteApprovalProcess")
	@ResponseBody
	public Map<String,Object> addAndDeleteApprovalProcess(HttpServletRequest request) {
		Map<String,Object> map=RequestUtil.getRequestParamByGeneric(request);
		dingTalkService.addAndDeleteApprovalProcess(map);
		return ResponseUtil.ResponseResult(ReturnStringUtil.UPDATE_SUCCESS);
	}
	/**
	 * 删除考勤审批流程设置（审核人）
	 * @param request
	 * @author 王荣
	 */
	@RequestMapping("/deleteApprovalProcessSet")
	@ResponseBody
	public Map<String,Object> deleteApprovalProcessSet(HttpServletRequest request) {
		Map<String,Object> map=RequestUtil.getRequestParamByGeneric(request);
		dingTalkService.deleteApprovalProcessSet(map);
		return ResponseUtil.ResponseResult(ReturnStringUtil.DELETE_SUCCESS);
	}
	/**
	 * 获取请假审批信息
	 * @param request
	 * @throws ServiceException
	 * @author 王荣
	 */
	@RequestMapping("/getApprovalProcessInfo")
	@ResponseBody
	public Map<String,Object> getApprovalProcessInfo(HttpServletRequest request) throws ServiceException {
		Map<String,Object> map=RequestUtil.getRequestParamByGeneric(request);
		return ResponseUtil.ResponseResult(dingTalkService.getApprovalProcessInfo(map));
	}
	/**
	 * 操作考勤审批单 目前仅用于请假、补卡
	 * @param request
	 * @return
	 * @author 王荣
	 */
	@RequestMapping("/updateAttendApproval")
	@ResponseBody
	public Map<String,Object> updateAttendApproval(HttpServletRequest request) {
		Map<String,Object> map=RequestUtil.getRequestParamByGeneric(request);
		dingTalkService.updateAttendApproval(map);
		return ResponseUtil.ResponseResult(ReturnStringUtil.UPDATE_SUCCESS);
	}
	/**
	 * 获取请假审批单信息
	 * @param request
	 * @throws ServiceException
	 * @author 王荣
	 */
	@RequestMapping("/getApprovalInfoById")
	@ResponseBody
	public Map<String,Object> getApprovalInfoById(HttpServletRequest request) throws ServiceException {
		Map<String,Object> map=RequestUtil.getRequestParamByGeneric(request);
		return ResponseUtil.ResponseResult(dingTalkService.getApprovalInfoById(map));
	}
	/**
	 * 修改职员工资明细
	 * @param request
	 * @return
	 * @author 王荣
	 */
	@RequestMapping("/updateFinanceDetail")
	@ResponseBody
	public Map<String,Object> updateFinancecDetail(HttpServletRequest request) {
		Map<String,Object> map = RequestUtil.getRequestParamByGeneric(request);
		dingTalkService.updateFinanceDetail(map);
		return ResponseUtil.ResponseResult(ReturnStringUtil.UPDATE_SUCCESS);
	}
	/**
	 * 获取奖惩制度设定信息
	 * @param request
	 * @return
	 * @throws ServiceException
	 * @author 王荣
	 */
	@RequestMapping("/selectRewardAndPunishInfo")
	@ResponseBody
	public Map<String,Object> selectRewardAndPunishInfo(HttpServletRequest request) throws ServiceException {
		Map<String,Object> map=RequestUtil.getRequestParamByGeneric(request);
		return ResponseUtil.ResponseResult(dingTalkService.selectRewardAndPunishInfo(map));
	}
	/**
	 * 查询月度汇总信息
	 * @param request
	 * @return
	 * @throws ParseException
	 * @author 王荣
	 */
	@RequestMapping("/querySummaryBody")
	@ResponseBody
	public Map querySummaryBody(HttpServletRequest request) throws ParseException{
		Map<String,Object> map=RequestUtil.getRequestParamByGeneric(request);
		return ResponseUtil.ResponseResult(dingTalkService.querySummaryBody(map));
	}
	/**
	 * 查询月度汇总信息
	 * @param request
	 * @return
	 * @throws ParseException
	 * @author 王荣
	 * @throws IOException 
	 * @throws IllegalAccessException 
	 * @throws IllegalArgumentException 
	 * @throws SecurityException 
	 * @throws NoSuchFieldException 
	 */
	@RequestMapping(value="/exportQuerySummaryBody",method=RequestMethod.GET)
	@ResponseBody
	public void exportQuerySummaryBody(HttpServletRequest request,HttpServletResponse response) throws ParseException, IOException, NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException{
		Map<String,Object> map=RequestUtil.getRequestParamByGeneric(request);
		List<SummaryBodyPojo> tableList = dingTalkService.querySummaryBody(map).getReturnData();
		ObjectMapper MAPPER = new ObjectMapper();
		//用于打印的数据
		List<SummaryBodyPojo> list = new ArrayList<SummaryBodyPojo>();
		//转换对象
		for(SummaryBodyPojo summaryBodyPojo : tableList) {
			String jsonStr = MAPPER.writeValueAsString(summaryBodyPojo);
			SummaryBodyPojo detail = MAPPER.readValue(jsonStr , SummaryBodyPojo.class);
			detail.setEarlyDurationStr(AttendanceUtil.getGapTime(detail.getEarlyDuration()));//早退
			detail.setLateDurationStr(AttendanceUtil.getGapTime(detail.getLateDuration()));//迟到
			detail.setWorkOvertimeDurationStr(AttendanceUtil.getGapTime(detail.getWorkOvertimeDuration()));//加班
			detail.setWorkTimeDurationStr(AttendanceUtil.getGapTime(detail.getWorkTimeDuration()));//工作时长
			detail.setLeaveDurationStr(AttendanceUtil.getGapTime(detail.getLeaveDuration()));//请假
			list.add(detail);
		}
		//表头字段
		String [] tableHeadFields={"姓名","部门","车间","工号","早退时长","迟到时长","请假时长","加班时长","工作时长","实发工资(元)"};
		//对应的内容字段
		String [] fields={"userName","deptName","workshopName","userId","earlyDurationStr","lateDurationStr","leaveDurationStr","workOvertimeDurationStr","workTimeDurationStr","realSalary"};
		String tempFolder=request.getServletContext().getRealPath("/")+"tempExcelFolder";
		File excelFile=ExcelExportUtil.createExcelFileWithStyle(list,tempFolder,tableHeadFields,fields,"考勤月度汇总");
		ResponseUtil.downloadfile(response, excelFile, "考勤月度汇总.xlsx", true);
	}
	/**
	 * 获取可选参与人员的信息
	 * @param request
	 * @author 王荣
	 */
	@RequestMapping("/getParticipantInfo")
	@ResponseBody
	public Map<String,String> getParticipantInfo(HttpServletRequest request){
		Map<String,String> map=RequestUtil.getRequestAllParam(request);
		return ResponseUtil.ResponseResult(dingTalkService.getParticipantInfo(map));
	}
	/**
	 * 添加考勤补卡审批记录
	 * @param request
	 * @author 王荣
	 */
	@RequestMapping("/insertAttendApprovalFillcard")
	@ResponseBody
	public Map<String,Object> insertAttendApprovalFillcard(HttpServletRequest request){
		Map<String,Object> map=RequestUtil.getRequestParamByGeneric(request);
		return ResponseUtil.ResponseResult(dingTalkService.insertAttendApprovalFillcard(map));
	}
	/**
	 * 获取与我相关的审批记录
	 * @param request
	 * @author 王荣
	 */
	@RequestMapping("/getMyApprovalList")
	@ResponseBody
	public Map<String,Object> getMyApprovalList(HttpServletRequest request){
		Map<String,Object> map=RequestUtil.getRequestParamByGeneric(request);
		return ResponseUtil.ResponseResult(dingTalkService.getMyApprovalList(map));
	}
	/**
	 * 获取审批单详情
	 * @param request
	 * @author 王荣
	 */
	@RequestMapping("/getApplicationDetailInfo")
	@ResponseBody
	public Map<String,Object> getApplicationDetailInfo(HttpServletRequest request){
		Map<String,Object> map=RequestUtil.getRequestParamByGeneric(request);
		return ResponseUtil.ResponseResult(dingTalkService.getApplicationDetailInfo(map));
	}
	/**
	 * 发送打卡成功消息
	 * @param request
	 * @author 王荣
	 */
	@RequestMapping(value="/sendClockMessage",method=RequestMethod.GET)
	@ResponseBody
	public void sendClockMessage(HttpServletRequest request) {
		Map<String,Object> map=RequestUtil.getRequestAllParamNotLogin(request);
		dingTalkService.sendClockMessage(map);
	}
	/**
	 * 导出原始记录
	 * @param request
	 * @return
	 * @author 王荣
	 */
	@RequestMapping(value="/exprotExcelAttendSourceRecord",method=RequestMethod.GET)
	@ResponseBody
	public void exportExcelAttendSourceRecord(HttpServletRequest request,HttpServletResponse response) throws ServiceException, CloneNotSupportedException, NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException, IOException{
		ObjectMapper MAPPER = new ObjectMapper();
		Map<String,Object> map=RequestUtil.getRequestParamByGeneric(request);
		map.put("start", null);
		map.put("length", null);
		DatatablesViewPageBean<AttendSourceRecordPojo> datatablesViewPageBean=dingTalkService.queryAttendance(map);
		List<AttendSourceRecordPojo> tableList= datatablesViewPageBean.getReturnData();
		//用于打印的数据
		List<AttendSourceRecordExportPojo> list = new ArrayList<AttendSourceRecordExportPojo>();
		//转换对象
		for(AttendSourceRecordPojo attendSourceRecordPojo : tableList) {
			String jsonStr = MAPPER.writeValueAsString(attendSourceRecordPojo);
			AttendSourceRecordExportPojo detail = MAPPER.readValue(jsonStr , AttendSourceRecordExportPojo.class);
			list.add(detail);
		}
		//表头字段
		String [] tableHeadFields={"姓名","部门","车间","工号","考勤日期","考勤时间","打卡时间","考勤结果","打卡地点"};
		//对应的内容字段
		String [] fields={"userName","deptName","workshopName","userId","workdate","baseCheckTime","userCheckTime","timeResult","location"};
		String tempFolder=request.getServletContext().getRealPath("/")+"tempExcelFolder";
		File excelFile=ExcelExportUtil.createExcelFileWithStyle(list,tempFolder,tableHeadFields,fields,"原始记录");
		ResponseUtil.downloadfile(response, excelFile, "考勤原始记录表.xlsx", true);
	}
	
	/**
	 * 导出原始记录 台州博士
	 * @param request
	 * @return
	 * @author 王荣
	 */
	@RequestMapping(value="/exprotExcelAttendSourceRecordTaiZhouBoShi",method=RequestMethod.GET)
	@ResponseBody
	public void exprotExcelAttendSourceRecordTaiZhouBoShi(HttpServletRequest request,HttpServletResponse response) throws ServiceException, CloneNotSupportedException, NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException, IOException{
		ObjectMapper MAPPER = new ObjectMapper();
		Map<String,Object> map=RequestUtil.getRequestParamByGeneric(request);
		map.put("start", null);
		map.put("length", null);
		DatatablesViewPageBean<AttendSourceRecordPojo> datatablesViewPageBean=dingTalkService.queryAttendance(map);
		List<AttendSourceRecordPojo> tableList= datatablesViewPageBean.getReturnData();
		//用于打印的数据
		List<AttendSourceRecordExportPojo> list = new ArrayList<AttendSourceRecordExportPojo>();
		//转换对象
		for(AttendSourceRecordPojo attendSourceRecordPojo : tableList) {
			String jsonStr = MAPPER.writeValueAsString(attendSourceRecordPojo);
			AttendSourceRecordExportPojo detail = MAPPER.readValue(jsonStr , AttendSourceRecordExportPojo.class);
			list.add(detail);
		}
		//表头字段
		String [] tableHeadFields={"姓名","部门","车间","工号","考勤日期","打卡时间","打卡无效时间"};
		//对应的内容字段
		String [] fields={"userName","deptName","workshopName","userId","workdate","userCheckTime","userCheckInvaildTime"};
		String tempFolder=request.getServletContext().getRealPath("/")+"tempExcelFolder";
		Map<String, List<AttendSourceRecordExportPojo>> detailmap = list.stream()
				.collect(Collectors.groupingBy(d -> fetchGroupKey(d) ));
		
		List<AttendSourceRecordExportPojo> returnList = new ArrayList<>();
		
		Map<String, List<AttendSourceRecordExportPojo>> result = new ArrayMap();
        //sort by key, a,b,c..., and put it into the "result" map
		detailmap.entrySet().stream()
                 .sorted(Map.Entry.comparingByKey())
                 .forEachOrdered(x -> result.put(x.getKey(), x.getValue()));
		
		result.forEach((k,v)->{
			AttendSourceRecordExportPojo bean = new AttendSourceRecordExportPojo();
			v.forEach(item->{
				bean.setUserName(item.getUserName());
				bean.setDeptName(item.getDeptName());
				bean.setWorkshopName(item.getWorkshopName());
				bean.setUserId(item.getUserId());
				bean.setWorkdate(item.getWorkdate().split(" ")[0]);
				bean.setUserCheckInvaildTime(item.getUserCheckInvaildTime());
				String userCheckTime =item.getUserCheckTime();
				
				if(userCheckTime!=null) {
					Date date = null;
					try {
						date = new SimpleDateFormat("yyyy-MM-dd HH:mm").parse(userCheckTime);
					} catch (ParseException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} 
					userCheckTime = new SimpleDateFormat("HH:mm").format(date);
				}else {
					userCheckTime = "     ";
				}
				
				bean.setUserCheckTime(((bean.getUserCheckTime()==null)?"":bean.getUserCheckTime())+" "+userCheckTime);
			});
			returnList.add(bean);
		});
				
		File excelFile=ExcelExportUtil.createExcelFileWithStyle(returnList,tempFolder,tableHeadFields,fields,"原始记录");
		ResponseUtil.downloadfile(response, excelFile, "考勤原始记录表.xlsx", true);
	}
	
	private String fetchGroupKey(AttendSourceRecordExportPojo detail){
        return detail.getWorkdate() 
        + detail.getUserName();
    }
	/**
	 * 导出打卡时间excel
	 * @param request
	 * @param response
	 * @throws ServiceException
	 * @throws CloneNotSupportedException
	 * @throws NoSuchFieldException
	 * @throws SecurityException
	 * @throws IllegalArgumentException
	 * @throws IllegalAccessException
	 * @throws IOException
	 * @author 王荣
	 */
	@RequestMapping(value="/exprotExcelAttendClockTime",method=RequestMethod.GET)
	@ResponseBody
	public void exprotExcelAttendClockTime(HttpServletRequest request,HttpServletResponse response) throws ServiceException, CloneNotSupportedException, NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException, IOException{
		Map<String,Object> requestParamMap=RequestUtil.getRequestParamByGeneric(request);
		requestParamMap.put("start", null);
		requestParamMap.put("length", null);
		String startDate = requestParamMap.get("startDate").toString();
		String endDate = requestParamMap.get("endDate").toString();
		
		SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd");
        Date sdate=null;
        Date eDate=null;
        try {
             sdate=df.parse(startDate);
             eDate=df.parse(endDate);
        } catch (ParseException e) {
              e.printStackTrace();
        }
        int betweendays = (int) ((eDate.getTime()-sdate.getTime())/(1000 * 60 * 60 *24)+0.5)+1;//天数
        Calendar c = Calendar.getInstance();
        List<String> dateList = new ArrayList<String>();
        while (sdate.getTime()<=eDate.getTime()) {
        	dateList.add(df.format(sdate));
			c.setTime(sdate);
			c.add(Calendar.DATE, 1); //日期加1天
			sdate = c.getTime();
		}
		
		List<ClockTimePojo> tableList= dingTalkService.queryClockTime(requestParamMap).getReturnData();
		List<Map<String, Object>> list = new ArrayList<Map<String,Object>>();
		for(ClockTimePojo clockTimePojo : tableList) {
			Map<String, Object> map = new HashMap<>();
			map.put("userName", clockTimePojo.getUserName());
			map.put("deptName", clockTimePojo.getDeptName());
			map.put("userId", clockTimePojo.getUserId());
			map.put("workShopName", clockTimePojo.getWorkshopName());
			List<String> clockList = clockTimePojo.getClockList();
			for(String date : dateList) {
				String clockStr = "";
				Iterator<String> it = clockList.iterator();
				while(it.hasNext()){
				    String clockTime = it.next();
				    try {
						if(TimeAndUnix.getDateDays(date, clockTime)==0) {
							clockTime = clockTime.substring(11, 16);
							clockStr += clockTime+"\n\r";
							it.remove();
						}else if(TimeAndUnix.getDateDays(date, clockTime)>0) {
							break;
						}
					} catch (ParseException e) {
						e.printStackTrace();
					}
				}
				map.put(date, clockStr);
			}
			list.add(map);
		}
		String[] tableHeadFields = new String[4+betweendays],fields = new String[4+betweendays];
		tableHeadFields[0] = "姓名";tableHeadFields[1] = "部门";tableHeadFields[2] = "车间";tableHeadFields[3] = "工号";
		fields[0] = "userName";fields[1] = "deptName";fields[2]="workShopName";fields[3] = "userId";
		for(int i=0;i<dateList.size();i++) {
			tableHeadFields[4+i] = dateList.get(i);
			fields[4+i] = dateList.get(i);
		}
		String tempFolder=request.getServletContext().getRealPath("/")+"tempExcelFolder";
		File excelFile=ExcelExportUtil.createExcelFileWithStyle(list,tempFolder,tableHeadFields,fields,"打卡时间");
		ResponseUtil.downloadfile(response, excelFile, "考勤打卡时间表.xlsx", true);
	}
	/**
	 * 查询每日统计
	 * @param request
	 * @return
	 * @author 王荣
	 * @throws ParseException 
	 */
	@RequestMapping("/queryDailyStatistics")
	@ResponseBody
	public Map<String,Object> queryDailyStatistics(HttpServletRequest request) throws ParseException{
		Map<String,Object> map=RequestUtil.getRequestParamByGeneric(request);
		return ResponseUtil.ResponseResult(dingTalkService.queryDailyStatistics(map));
	}
	/**
	 * 查询考勤设备信息
	 * @param request
	 * @return
	 * @author 王荣
	 */
	@RequestMapping("/queryAttendDevice")
	@ResponseBody
	public DatatablesViewPageBean<AttendDevicePojo> queryAttendDevice(HttpServletRequest request){
		Map<String,Object> map=RequestUtil.getRequestParamByGeneric(request);
		return dingTalkService.queryAttendDevice(map);
	}
	/**
	 * 添加考勤机
	 * @param request
	 * @return
	 * @author 王荣
	 */
	@RequestMapping("/insertAttendDevice")
	@ResponseBody
	public Map<String,Object> insertAttendDevice(HttpServletRequest request) {
		Map<String,Object> map=RequestUtil.getRequestParamByGeneric(request);
		dingTalkService.insertAttendDevice(map);
		return ResponseUtil.ResponseResult(ReturnStringUtil.ADD_SUCCESS);
	}
	/**
	 * 删除考勤机
	 * @param request
	 * @return
	 * @author 王荣
	 */
	@RequestMapping("/deleteAttendDevice")
	@ResponseBody
	public Map<String,Object> deleteAttendDevice(HttpServletRequest request){
		Map<String,Object> map=RequestUtil.getRequestParamByGeneric(request);
		dingTalkService.deleteAttendDevice(map);
		return ResponseUtil.ResponseResult(ReturnStringUtil.DELETE_SUCCESS);
	}
	/**
	 * 修改考勤机名称
	 * @param request
	 * @return
	 * @author 王荣
	 */
	@RequestMapping("/updateAttendDevice")
	@ResponseBody
	public Map<String,Object> updateAttendDevice(HttpServletRequest request){
		Map<String,Object> map=RequestUtil.getRequestParamByGeneric(request);
		dingTalkService.updateAttendDevice(map);
		return ResponseUtil.ResponseResult(ReturnStringUtil.UPDATE_SUCCESS);
	}
	/**
	 * 获取考勤机设备信息
	 * @param request
	 * @return
	 * @author 王荣
	 */
	@RequestMapping("/getAttendDevice")
	@ResponseBody
	public Map<String,Object> getAttendDevice(HttpServletRequest request){
		Map<String,Object> map=RequestUtil.getRequestParamByGeneric(request);
		return ResponseUtil.ResponseResult(dingTalkService.getAttendDevice(map));
	}
	/**
	 * 获取考勤机设备的用户
	 * @param request
	 * @return
	 * @author 王荣
	 */
	@RequestMapping("/getAttendDeviceUsers")
	@ResponseBody
	public Map<String,Object> getAttendDeviceUsers(HttpServletRequest request){
		Map<String,Object> map=RequestUtil.getRequestParamByGeneric(request);
		return ResponseUtil.ResponseResult(dingTalkService.getAttendDeviceUsers(map));
	}
	/**
	 * 修改设备管理员
	 * @param request
	 * @return
	 * @author 王荣
	 */
	@RequestMapping(value="/insertAndDeleteAttendDeviceManager")
	@ResponseBody
	public Map<String,Object> insertAndDeleteAttendDeviceManager(HttpServletRequest request){
		Map<String,Object> map=RequestUtil.getRequestParamByGeneric(request);
		dingTalkService.insertAndDeleteAttendDeviceManager(map);
		return ResponseUtil.ResponseResult(ReturnStringUtil.UPDATE_SUCCESS);
	}
	/**
	 * 查询请假审批记录
	 * @param request
	 * @author 王荣
	 */
	@RequestMapping(value="/queryLeaveApplicationRecord")
	@ResponseBody
	public DatatablesViewPageBean<LeaveApplicationPojo> queryLeaveApplicationRecord(HttpServletRequest request){
		Map<String,Object> map=RequestUtil.getRequestParamByGeneric(request);
		return dingTalkService.queryLeaveApplicationRecord(map);
	}
	/**
	 * 查询补卡审批记录
	 * @param request
	 * @author 王荣
	 */
	@RequestMapping(value="/queryFillcardApplicationRecord")
	@ResponseBody
	public DatatablesViewPageBean<FillcardApplicationPojo> queryFillcardApplicationRecord(HttpServletRequest request){
		Map<String,Object> map=RequestUtil.getRequestParamByGeneric(request);
		return dingTalkService.queryFillcardApplicationRecord(map);
	}
	
	/**
	 * 查询加班审批记录
	 * @param request
	 * @return
	 * @author 王荣
	 */
	@RequestMapping(value="/queryOvertimeApplicationRecord")
	@ResponseBody
	public DatatablesViewPageBean<OvertimeApplicationPojo> queryOvertimeApplicationRecord(HttpServletRequest request){
		Map<String,Object> map=RequestUtil.getRequestParamByGeneric(request);
		return dingTalkService.queryOvertimeApplicationRecord(map);
	}
	
	/**
	 * 查看打卡时间
	 * @param request
	 * @author 王荣
	 */
	@RequestMapping(value="/queryClockTime")
	@ResponseBody
	public DatatablesViewPageBean<ClockTimePojo> queryClockTime(HttpServletRequest request){
		Map<String,Object> map=RequestUtil.getRequestParamByGeneric(request);
		return dingTalkService.queryClockTime(map);
	}
	/**
	 * 导出请假审批记录
	 * @param request
	 * @param response
	 * @throws ServiceException
	 * @throws CloneNotSupportedException
	 * @throws NoSuchFieldException
	 * @throws SecurityException
	 * @throws IllegalArgumentException
	 * @throws IllegalAccessException
	 * @throws IOException
	 * @author 王荣
	 */
	@RequestMapping(value="/exprotExcelLeaveApplicationRecord",method=RequestMethod.GET)
	@ResponseBody
	public void exprotExcelLeaveApplicationRecord(HttpServletRequest request,HttpServletResponse response) throws ServiceException, CloneNotSupportedException, NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException, IOException{
		Map<String,Object> requestParamMap=RequestUtil.getRequestParamByGeneric(request);
		requestParamMap.put("start", null);
		requestParamMap.put("length", null);
		List<LeaveApplicationPojo> tableList= dingTalkService.queryLeaveApplicationRecord(requestParamMap).getReturnData();
		List<Map<String, Object>> list= new ArrayList<Map<String, Object>>();
		for(LeaveApplicationPojo pojo : tableList) {
			Map<String,Object> map = new HashMap<String,Object>();
			map.put("approvalNo", pojo.getApprovalNo());
			String leaveType = "";
			switch((Integer)pojo.getLeaveType()) {
			case 1 : leaveType = "年假";break;
			case 2 : leaveType = "事假";break;
			case 3 : leaveType = "病假";break;
			case 4 : leaveType = "调休";break;
			case 5 : leaveType = "产假";break;
			case 6 : leaveType = "陪产假";break;
			case 7 : leaveType = "婚假";break;
			case 8 : leaveType = "例假";break;
			case 9 : leaveType = "丧假";break;
			case 10 : leaveType = "公出";break;
			}
			map.put("leaveType", leaveType);
			map.put("startTime", pojo.getStartTime());
			map.put("endTime", pojo.getEndTime());
			map.put("duration", pojo.getDuration());
			map.put("reason", pojo.getReason());
			String stateStr = "";
			switch((Integer)pojo.getState()) {
			case 0 : stateStr = "等待审批";break;
			case 1 : stateStr = "审批通过";break;
			case 2 : stateStr = "审批退回";break;
			case 3 : stateStr = "撤销";
			}
			map.put("state", stateStr);
			map.put("submitterName", pojo.getSubmitterName());
			map.put("deptName", pojo.getDeptName());
			map.put("createTime", pojo.getCreateTime());
			String record = pojo.getSubmitterName()+"|"+pojo.getCreateTime()+"|提交申请；";
			List<Map<String, Object>> processList = pojo.getLeaveProcessList();
			for(Map<String, Object> tMap : processList) {
				Integer dealwithState = (Integer) tMap.get("dealwithState");
				String dealwithStateStr = "";
				switch(dealwithState) {
				case 0 : dealwithStateStr = "未审批";break;
				case 1 : dealwithStateStr = "同意";break;
				case 2 : dealwithStateStr = "退回";break;
				case 3 : dealwithStateStr = "撤销";break;
				case 4 : dealwithStateStr = "转交";
				}
				record += "\n\r"+tMap.get("approverName")+"|"+tMap.get("dealwithTime")+"|"+dealwithStateStr+"；";
			}
			map.put("record", record);
			list.add(map);
		}
		String [] tableHeadFields={"审批编号","请假类型","开始时间","结束时间","时长（小时）","请假事由","审批状态","审批记录","提交人","部门","提交时间"};
		String [] fields={"approvalNo","leaveType","startTime","endTime","duration","reason","state","record","submitterName","deptName","createTime"};
		String tempFolder=request.getServletContext().getRealPath("/")+"tempExcelFolder";
		File excelFile=ExcelExportUtil.createExcelFileWithStyle(list,tempFolder,tableHeadFields,fields,"请假审批记录");
		ResponseUtil.downloadfile(response, excelFile, "请假审批记录表.xlsx", true);
	}
	/**
	 * 获取考勤组按月排班
	 * @param request
	 * @author 王荣
	 */
	@RequestMapping(value="/getGroupMonthlyPlan")
	@ResponseBody
	public Map<String, Object> getGroupMonthlyPlan(HttpServletRequest request){
		Map<String,Object> requestMap = RequestUtil.getRequestParamByGeneric(request);
		return ResponseUtil.ResponseResult(dingTalkService.getGroupMonthlyPlan(requestMap));
	}
	/**
	 * 保存考勤加班规则
	 * @param request
	 * @author 王荣
	 */
	@RequestMapping(value="/saveAttendOvertimeRule")
	@ResponseBody
	public Map<String, Object> saveAttendOvertimeRule(HttpServletRequest request){
		Map<String,Object> requestParam = RequestUtil.getRequestParamByGeneric(request);
		dingTalkService.saveAttendOvertimeRule(requestParam);
		return ResponseUtil.ResponseResult(ReturnStringUtil.SAVE_SUCCESS);
	}
	/**
	 * 查询考勤加班规则
	 * @param request
	 * @author 王荣
	 */
	@RequestMapping(value="/queryAttendOvertimeRule")
	@ResponseBody
	public DatatablesViewPageBean<OvertimeRulePojo> queryAttendOvertimeRule(HttpServletRequest request) {
		Map<String,Object> requestParam = RequestUtil.getRequestParamByGeneric(request);
		return dingTalkService.queryAttendOvertimeRule(requestParam);
	}
	/**
	 * 删除考勤加班规则
	 * @param request
	 * @author 王荣
	 */
	@RequestMapping(value="/deleteAttendOvertimeRule")
	@ResponseBody
	public Map<String, Object> deleteAttendOvertimeRule(HttpServletRequest request){
		Map<String,Object> requestParam = RequestUtil.getRequestParamByGeneric(request);
		dingTalkService.deleteAttendOvertimeRule(requestParam);
		return ResponseUtil.ResponseResult(ReturnStringUtil.DELETE_SUCCESS);
	}
	/**
	 * 修改考勤加班规则
	 * @param request
	 * @author 王荣
	 */
	@RequestMapping(value="/updateAttendOvertimeRule")
	@ResponseBody
	public Map<String, Object> updateAttendOvertimeRule(HttpServletRequest request){
		Map<String, Object> requestParam = RequestUtil.getRequestParamByGeneric(request);
		dingTalkService.updateAttendOvertimeRule(requestParam);
		return ResponseUtil.ResponseResult(ReturnStringUtil.UPDATE_SUCCESS);
	}
	/**
	 * 保存加班审批单
	 * @param request
	 * @param bean
	 * @author 王荣
	 */
	@RequestMapping(value="saveOvertimeApplication")
	@ResponseBody
	public Map<String, Object> saveOvertimeApplication(HttpServletRequest request,AttendApprovalOvertimeBean bean){
		Map<String, Object> requestParam = RequestUtil.getRequestParamByGeneric(request);
		return ResponseUtil.ResponseResult(dingTalkService.saveOvertimeApplication(requestParam));
	}
	/**
	 * 操作加班审批单
	 * @param request
	 * @author 王荣
	 */
	@RequestMapping(value="updateAttendOvertimeApplication")
	@ResponseBody
	public Map<String, Object> updateAttendOvertimeApplication(HttpServletRequest request){
		Map<String, Object> requestParam = RequestUtil.getRequestParamByGeneric(request);
		dingTalkService.updateAttendOvertimeApplication(requestParam);
		return ResponseUtil.ResponseResult(ReturnStringUtil.UPDATE_SUCCESS);
	}
	
	/**
	 * 操作加班审批单批量操作
	 * @param request
	 * @author 王荣
	 */
	@RequestMapping(value="updateAttendOvertimeApplicationBatch")
	@ResponseBody
	public Map<String, Object> updateAttendOvertimeApplicationBatch(HttpServletRequest request){
		Map<String, Object> requestParam = RequestUtil.getRequestParamByGeneric(request);
		dingTalkService.updateAttendOvertimeApplicationBatch(requestParam);
		return ResponseUtil.ResponseResult(ReturnStringUtil.UPDATE_SUCCESS);
	}
	
	/**
	 * 导出每日统计，写的太渣了，自己都不想用
	 * @param request
	 * @param response
	 * @throws NoSuchFieldException
	 * @throws SecurityException
	 * @throws IllegalArgumentException
	 * @throws IllegalAccessException
	 * @throws IOException 
	 * @author 王荣
	 * @throws ParseException 
	 */
	@RequestMapping(value="/exportDailyStatictics",method=RequestMethod.GET)
	public void exportDailyStatictics(HttpServletRequest request,HttpServletResponse response) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException, IOException, ParseException {
		Map<String,Object> requestMap=RequestUtil.getRequestParamByGeneric(request);
		requestMap.put("start", null);
		requestMap.put("length", null);
		long queryStartTime = new DateTime().getMillis();
		DatatablesViewPageBean<AttendQueryDailyStatisticsPojo> datatablesViewPageBean = dingTalkService.queryDailyStatistics(requestMap);
		long queryEndTime = new DateTime().getMillis();
		System.out.println("查询数据花费时长："+(queryEndTime-queryStartTime)+"ms");
		List<AttendQueryDailyStatisticsPojo> attendQueryDailyStatisticsPojos = datatablesViewPageBean.getReturnData();
		//表头list，对应内容字段list
		List<String> headList = new ArrayList<>(),bodyList = new ArrayList<>();
		//打卡时间list，打卡结果list
		List<String> bodyClockList = new ArrayList<>(),bodyResultList = new ArrayList<>();
		bodyList.add("userName");headList.add("姓名");
		bodyList.add("userId");headList.add("工号");
		bodyList.add("deptName");headList.add("部门");
		bodyList.add("workdate");headList.add("日期");
		bodyList.add("className");headList.add("班次");
		List<Map<String, String>> list = new ArrayList<>();
		for(AttendQueryDailyStatisticsPojo attendQueryDailyStatisticsPojo : attendQueryDailyStatisticsPojos) {
			if(attendQueryDailyStatisticsPojo.getGroupName()==null) continue;
			Map<String, String> rowData = new HashMap<>();
			rowData.put("userName", attendQueryDailyStatisticsPojo.getUserName());
			rowData.put("userId", String.valueOf(attendQueryDailyStatisticsPojo.getUserId()));
			rowData.put("deptName", attendQueryDailyStatisticsPojo.getDeptName());
			rowData.put("workdate", attendQueryDailyStatisticsPojo.getWorkdate());
			String className = attendQueryDailyStatisticsPojo.getClassName();
			rowData.put("className", className==null ? "休息" : className+" "+attendQueryDailyStatisticsPojo.getAttendanceTime());
			//请假信息
			List<Map<String, Object>> leaveList = attendQueryDailyStatisticsPojo.getLeaveList();
			StringBuffer relationLeaveInfo = new StringBuffer();
			for(Map<String, Object> leaveMap : leaveList) {
				String type = AttendApprovalLeaveBean.LEAVE_TYPE.get(leaveMap.get("type"));
				String startTime = leaveMap.get("startTime").toString();
				String endTime = leaveMap.get("endTime").toString();
				String duration = leaveMap.get("duration").toString();
				if(relationLeaveInfo.length()>0) relationLeaveInfo.append("\r\n");
				relationLeaveInfo.append(type+" ")
					.append(new DateTime(Long.valueOf(startTime)).toString("MM-dd HH:mm")+" ")
					.append(new DateTime(Long.valueOf(endTime)).toString("MM-dd HH:mm")+" ")
					.append(duration+"小时");
			}
			rowData.put("leaveInfo", relationLeaveInfo.toString());
			//打卡信息
			List<Map<String, Object>> clockList = attendQueryDailyStatisticsPojo.getClockList();
			//遍历打卡数据，转换为Map.put("上班1打卡"，打卡时间).put("上班1结果"，打卡结果)
			for(int i=0;i<clockList.size();i++) {
				Map<String, Object> clockMap = clockList.get(i);
				if(i+1>bodyClockList.size()) bodyClockList.add("clock"+i);
				String clockKey = bodyClockList.get(i);
				if(i+1>bodyResultList.size()) bodyResultList.add("result"+i);
				String resultKey = bodyResultList.get(i);
				rowData.put(clockKey, clockMap.get("userCheckTime")==null ? "" : new DateTime(Long.valueOf(clockMap.get("userCheckTime").toString())).toString("HH:mm"));
				String timeResult = "";
				String result = clockMap.get("timeResult").toString();
				//转换打卡结果
				switch (result) {
				case AttendanceUtil.TIME_RESULT_NORMAL: timeResult = "正常";break;
				case AttendanceUtil.TIME_RESULT_LATE: timeResult = "迟到";break;
				case AttendanceUtil.TIME_RESULT_EARLY: timeResult = "早退";break;
				case AttendanceUtil.TIME_RESULT_LACK: timeResult = "缺卡";break;
				}
				//判断是否为请假
				if(AttendanceUtil.TIME_RESULT_LACK.equals(result) || AttendanceUtil.TIME_RESULT_NORMAL.equals(result)) {
					long baseCheckTime = Long.valueOf(clockMap.get("baseCheckTime").toString());
					for(Map<String, Object> leaveMap : leaveList) {
						if(Long.valueOf(leaveMap.get("startTime").toString())<=baseCheckTime
								&& baseCheckTime<=Long.valueOf(leaveMap.get("endTime").toString())) {
							timeResult = "请假";break;
						}
					}
				}
				rowData.put(resultKey, timeResult);
			}
			list.add(rowData);
		}
		//添加上下班1，2到bodyList、headList
		for(int i=0;i<bodyClockList.size();i++) {
			bodyList.add(bodyClockList.get(i));
			bodyList.add(bodyResultList.get(i));
			String clockPrefix = null;
			switch (i%2) {
			case 0:
				clockPrefix = "上班"+(i/2+1);
				break;
			default:
				clockPrefix = "下班"+(i/2+1);
				break;
			}
			headList.add(clockPrefix+"打卡");
			headList.add(clockPrefix+"结果");
		}
		bodyList.add("leaveInfo");headList.add("关联的审批单");
		String[] bodyArray = new String[bodyList.size()];
		String[] headArray = new String[headList.size()];
		String tempFolder=request.getServletContext().getRealPath("/")+"tempExcelFolder";
		long exportStart = System.currentTimeMillis();
		System.out.println("中间处理花费时长："+(exportStart-queryEndTime)+"ms");
		File excelFile=ExcelExportUtil.createExcelFileWithStyle(list, tempFolder, headList.toArray(headArray), bodyList.toArray(bodyArray), "每日统计");
		long exportEnd = System.currentTimeMillis();
		System.out.println("生成excel文件花费时长："+(exportEnd-exportStart)+"ms");
		ResponseUtil.downloadfile(response, excelFile, "每日统计.xlsx", true);
	}
	
	/**
	 * 外出打卡
	 */
	@RequestMapping(value="/dkOutSide")
	@ResponseBody
	public Map<String, Object>  dkOutSide(HttpServletRequest request) {
		Map<String,Object> requestMap=RequestUtil.getRequestParamByGeneric(request);
		//查询设备ID
		List<PersonBean> beans = basicDataService.getPersonDetail(requestMap.get("loginUserId").toString());
		return ResponseUtil.ResponseResult(dingTalkService.dkOutSide(requestMap,beans));
	}

	/**
	 * 添加报销申请审批
	 */
	@RequestMapping(value="/insertReimburse")
	@ResponseBody
	public Map<String,Object> insertReimburse(HttpServletRequest request){
		Map<String,Object> map=RequestUtil.getRequestParamByGeneric(request);
		return ResponseUtil.ResponseResult(dingTalkService.insertReimburse(map));
	}
	/**
	 * 操作报销审批单
	 * @param request
	 * @return
	 */
	@RequestMapping("/updateAttendApprovalForReimburse")
	@ResponseBody
	public Map<String,Object> updateAttendApprovalForReimburse(HttpServletRequest request) {
		Map<String,Object> map=RequestUtil.getRequestParamByGeneric(request);
		dingTalkService.updateAttendApprovalForReimburse(map);
		return ResponseUtil.ResponseResult(ReturnStringUtil.UPDATE_SUCCESS);
	}
	
	/**
	 * 查询报销审批记录
	 * @param request
	 * @return
	 * @author 王荣
	 */
	@RequestMapping(value="/queryReimburseRecord")
	@ResponseBody
	public DatatablesViewPageBean<OvertimeApplicationPojo> queryReimburseRecord(HttpServletRequest request){
		Map<String,Object> map=RequestUtil.getRequestParamByGeneric(request);
		return dingTalkService.queryReimburseRecord(map);
	}
	
	/**
	 * 添加行政处罚申请审批
	 */
	@RequestMapping(value="/insertAdministrativePenalty")
	@ResponseBody
	public Map<String,Object> insertAdministrativePenalty(HttpServletRequest request){
		Map<String,Object> map=RequestUtil.getRequestParamByGeneric(request);
		return ResponseUtil.ResponseResult(dingTalkService.insertAdministrativePenalty(map));
	}
	/**
	 * 操作行政处罚审批单
	 * @param request
	 * @return
	 */
	@RequestMapping("/updateAttendApprovalForAdministrativePenalty")
	@ResponseBody
	public Map<String,Object> updateAttendApprovalForAdministrativePenalty(HttpServletRequest request) {
		Map<String,Object> map=RequestUtil.getRequestParamByGeneric(request);
		dingTalkService.updateAttendApprovalForAdministrativePenalty(map);
		return ResponseUtil.ResponseResult(ReturnStringUtil.UPDATE_SUCCESS);
	}
	
	/**
	 * 查询行政处罚审批记录
	 * @param request
	 * @return
	 * @author 王荣
	 */
	@RequestMapping(value="/queryAdministrativePenaltyRecord")
	@ResponseBody
	public DatatablesViewPageBean<OvertimeApplicationPojo> queryAdministrativePenaltyRecord(HttpServletRequest request){
		Map<String,Object> map=RequestUtil.getRequestParamByGeneric(request);
		return dingTalkService.queryAdministrativePenaltyRecord(map);
	}
	
	/**
	 * 导出加班审批记录
	 * @param request
	 * @param response
	 * @throws ServiceException
	 * @throws CloneNotSupportedException
	 * @throws NoSuchFieldException
	 * @throws SecurityException
	 * @throws IllegalArgumentException
	 * @throws IllegalAccessException
	 * @throws IOException
	 * @author 王荣
	 */
	@RequestMapping(value="/exprotExcelOvertimeApplicationRecord",method=RequestMethod.GET)
	@ResponseBody
	public void exprotExcelOvertimeApplicationRecord(HttpServletRequest request,HttpServletResponse response) throws ServiceException, CloneNotSupportedException, NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException, IOException{
		Map<String,Object> requestParamMap=RequestUtil.getRequestParamByGeneric(request);
		requestParamMap.put("start", null);
		requestParamMap.put("length", null);
		List<OvertimeApplicationPojo> tableList= dingTalkService.queryOvertimeApplicationRecord(requestParamMap).getReturnData();
		List<Map<String, Object>> list= new ArrayList<Map<String, Object>>();
		for(OvertimeApplicationPojo pojo : tableList) {
			Map<String,Object> map = new HashMap<String,Object>();
			map.put("approvalNo", pojo.getApprovalNo());
			map.put("startTime", pojo.getStartTime());
			map.put("endTime", pojo.getEndTime());
			map.put("duration", pojo.getDuration());
			map.put("reason", pojo.getReason());
			String stateStr = "";
			switch((Integer)pojo.getState()) {
			case 0 : stateStr = "等待审批";break;
			case 1 : stateStr = "审批通过";break;
			case 2 : stateStr = "审批退回";break;
			case 3 : stateStr = "撤销";
			}
			map.put("state", stateStr);
			map.put("submitterName", pojo.getSubmitterName());
			map.put("deptName", pojo.getDeptName());
			map.put("createTime", pojo.getCreateTime());
			String record = pojo.getSubmitterName()+"|"+pojo.getCreateTime()+"|提交申请；";
			List<Map<String, Object>> processList = pojo.getProcessList();
			for(Map<String, Object> tMap : processList) {
				Integer dealwithState = (Integer) tMap.get("dealwithState");
				String dealwithStateStr = "";
				switch(dealwithState) {
				case 0 : dealwithStateStr = "未审批";break;
				case 1 : dealwithStateStr = "同意";break;
				case 2 : dealwithStateStr = "退回";break;
				case 3 : dealwithStateStr = "撤销";break;
				case 4 : dealwithStateStr = "转交";
				}
				record += "\n\r"+tMap.get("approverName")+"|"+tMap.get("dealwithTime")+"|"+dealwithStateStr+"；";
			}
			map.put("record", record);
			list.add(map);
		}
		String [] tableHeadFields={"审批编号","开始时间","结束时间","时长（小时）","加班原因","审批状态","审批记录","提交人","部门","提交时间"};
		String [] fields={"approvalNo","startTime","endTime","duration","reason","state","record","submitterName","deptName","createTime"};
		String tempFolder=request.getServletContext().getRealPath("/")+"tempExcelFolder";
		File excelFile=ExcelExportUtil.createExcelFileWithStyle(list,tempFolder,tableHeadFields,fields,"加班审批记录");
		ResponseUtil.downloadfile(response, excelFile, "加班审批记录表.xlsx", true);
	}

	/**
	 * 设置考勤班次打卡有效时间
	 */
	@RequestMapping(value="/insertAttendClassTail")
	@ResponseBody
	public Map<String,Object> insertAttendClassTail(HttpServletRequest request ){
		Map<String,Object> map=RequestUtil.getRequestParamByGeneric(request);
		List<AttendClassTailBean> beans = JSONObject.parseArray(map.get("beans").toString(), AttendClassTailBean.class);
		dingTalkService.insertAttendClassTail(beans,map);
		return ResponseUtil.ResponseResult("设置成功");
	}
	
	/**
	 * 设置考勤班次打卡有效时间
	 */
	@RequestMapping(value="/getAttendClassTail")
	@ResponseBody
	public Map<String,Object> getAttendClassTail(HttpServletRequest request){
		Map<String,Object> map=RequestUtil.getRequestParamByGeneric(request);
		return ResponseUtil.ResponseResult(dingTalkService.getAttendClassTail(map));
	}
	
	
	@RequestMapping(value="/getCodeAreaByCodeId")
	@ResponseBody
	public Map<String,Object> getCodeAreaByCodeId(HttpServletRequest request){
		Map<String,Object> map=RequestUtil.getRequestParamByGeneric(request);
		String codeName = map.get("codeName").toString();
		if("瑞安码".equals(codeName)) {
			return ResponseUtil.ResponseResult(dingTalkService.getCodeAreaByCodeIdForRuianCode(map));
		}
		return ResponseUtil.ResponseResult(null);
	}
	
	@RequestMapping(value="/getTokenForRuianCode")
	@ResponseBody
	public Map<String,Object> getTokenForRuianCode(HttpServletRequest request){
		Map<String,Object> map=RequestUtil.getRequestParamByGeneric(request);
		int rannum= (int)(new Random().nextDouble()*(99999-10000 + 1))+ 10000;
		RedisCache.setDataToRedis("getTokenForRuianCode"+map.get("loginCompany"), rannum, "100");
		
		String accessToken=weiXinService.getAccessToken(null); 
		JSONObject data=WeixinTemplateList.packJsonToValidCode("您好，"+map.get("loginCompany")+"修改地方码验证码已发送给您", rannum+"", "", "请在验证界面输入验证码", null, null, null, null);
		for (String openId : Arrays.asList("o_THqw1024CEL8NDrHgnV5wgIL6A" ,"o_THqw9VP81Ut137qpajF1u79zgA" , 
				"o_THqw0_UhnWghEzp4DCHVZb23f8" , "o_THqw0TJcxQLDEwiBFYh7xtaT18")) {
			WeixinTemplateSender.sendWechatmsgToUser(openId, "9SNq1d6Wed02ZqPqb8tkCvVUIQ7pXq69Fr3nrUcKP0A", null, data, accessToken);
		}
		return ResponseUtil.ResponseResult("验证码已发送");
	}
	
	@RequestMapping(value="/checkTokenForRuianCode")
	@ResponseBody
	public Map<String,Object> checkTokenForRuianCode(HttpServletRequest request){
		Map<String,Object> map=RequestUtil.getRequestParamByGeneric(request);
		String token = map.get("token").toString();
		String realToken = String.valueOf(RedisCache.getDataFromRedis("getTokenForRuianCode"+map.get("loginCompany")));
		if (token.equals(realToken)) {
			RedisCache.setDataToRedis("getTokenForRuianCode"+map.get("loginCompany"), "", "0");//失效
			return ResponseUtil.ResponseResult("校验成功");
		}
		return ResponseUtil.ResponseError("校验错误");
	}

	/**
	 * 导出补卡审批记录
	 * @param request
	 * @param response
	 * @throws ServiceException
	 * @throws CloneNotSupportedException
	 * @throws NoSuchFieldException
	 * @throws SecurityException
	 * @throws IllegalArgumentException
	 * @throws IllegalAccessException
	 * @throws IOException
	 * @author 王荣
	 */
	@RequestMapping(value="/exprotFillcardApplicationRecord",method=RequestMethod.GET)
	@ResponseBody
	public void exprotFillcardApplicationRecord(HttpServletRequest request,HttpServletResponse response) throws ServiceException, CloneNotSupportedException, NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException, IOException{
		Map<String,Object> requestParamMap=RequestUtil.getRequestParamByGeneric(request);
		requestParamMap.put("start", null);
		requestParamMap.put("length", null);
		List<FillcardApplicationPojo> tableList= dingTalkService.queryFillcardApplicationRecord(requestParamMap).getReturnData();
		List<Map<String, Object>> list= new ArrayList<Map<String, Object>>();
		for(FillcardApplicationPojo pojo : tableList) {
			Map<String,Object> map = new HashMap<String,Object>();
			map.put("approvalNo", pojo.getApprovalNo());
			map.put("baseCheckTime", pojo.getBaseCheckTime());
			map.put("reason", pojo.getReason());
			String stateStr = "";
			switch((Integer)pojo.getState()) {
				case 0 : stateStr = "等待审批";break;
				case 1 : stateStr = "审批通过";break;
				case 2 : stateStr = "审批退回";break;
				case 3 : stateStr = "撤销";
			}
			map.put("state", stateStr);
			map.put("submitterName", pojo.getSubmitterName());
			map.put("deptName", pojo.getDeptName());
			map.put("createTime", pojo.getCreateTime());

			String record = pojo.getSubmitterName()+"|"+pojo.getCreateTime()+"|提交申请；";
			List<Map<String, Object>> processList = pojo.getProcessList();
			for(Map<String, Object> tMap : processList) {
				Integer dealwithState = (Integer) tMap.get("dealwithState");
				String dealwithStateStr = "";
				switch(dealwithState) {
					case 0 : dealwithStateStr = "未审批";break;
					case 1 : dealwithStateStr = "同意";break;
					case 2 : dealwithStateStr = "退回";break;
					case 3 : dealwithStateStr = "撤销";break;
					case 4 : dealwithStateStr = "转交";
				}
				record += "\n\r"+tMap.get("approverName")+"|"+tMap.get("dealwithTime")+"|"+dealwithStateStr+"；";
			}
			map.put("record", record);
			list.add(map);
		}

		String [] tableHeadFields={"审批编号","打卡时间","缺卡原因","审批状态","审批记录","提交人","部门","提交时间"};
		String [] fields={"approvalNo","baseCheckTime","reason","state","record","submitterName","deptName","createTime"};
		String tempFolder=request.getServletContext().getRealPath("/")+"tempExcelFolder";
		File excelFile=ExcelExportUtil.createExcelFileWithStyle(list,tempFolder,tableHeadFields,fields,"请假审批记录");
		ResponseUtil.downloadfile(response, excelFile, "补卡审批记录表.xlsx", true);
	}
	
}
